package com.sky.service.user.Impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";


    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;


    @Autowired
    MerchantMapper  merchantMapper;

    @Autowired
    JwtProperties jwtProperties;

    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {
        //调用微信小程序接口，换取用户的openid
        String openId = getOpenId(dto.getCode());

        //根据openid查询用户信息，如果查不到，说明是新用户，保存入库
        User user = userMapper.getByOpenId(openId);
        if (user == null){
            User user1 = new User();
            user1.setOpenid(openId);
            user1.setCreateTime(LocalDateTime.now());
            userMapper.insert(user1);

        }
        //如果查询到，根据id生成token，返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token= JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);


        //查询商家信息
        Merchant merchant = merchantMapper.getById(1l);
        //配送费计算

        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, dto.getLocation());

        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .token(token)
                .openid(openId)
                .shopAddress(merchant.getShopAddress())
                .shopId(merchant.getId())
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .deliveryFee(delivoryCost)
                .build();
        return Result.success(userLoginVO);
    }

    private String getOpenId(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, params);
        Map map = JSON.parseObject(json,Map.class);
        return map.get("openid").toString();
    }
}
